<?php
/**
 * ===============================================
 * 版权所有 2019-2050 青岛铁锤科技有限公司，并保留所有权利。
 * 网站地址: http://www.huaxianling.com
 * ===============================================
 * Author: Rag Hu
 * Created Time: 2019/6/25 16:31
 * Modified Time: 2019/6/25 16:31
 * Version: 2.0
 */

namespace App\Modules\System\Repositories;


use App\Exceptions\NotFoundException;
use App\Lib\Utilities;
use App\Models\UserStore;
use App\Modules\Member\Repositoryies\ScheduleRepository;
use App\Modules\System\Criterias\GetFindStoreBarberListCriteria;
use Flower\Core\Repository\Eloquent\BaseRepository;
use Illuminate\Support\Facades\DB;

class UserStoreRepository extends BaseRepository
{
	public function model()
	{
		return UserStore::class;
	}

	public function createUserStore($store_id, $user_id, $rid, $is_default = 0)
	{
		$new_user_store_data = [
			'sid'        => $store_id,
			'uid'        => $user_id,
			'rid'        => $rid,
			'is_work'    => 1,
			'is_default' => $is_default,
		];
		return $this->create($new_user_store_data);
	}

	public function roles($userId, $storeId = null)
	{
		$map = empty($storeId) ? ['uid' => $userId] : [
			'uid' => $userId,
			'sid' => $storeId
		];
		return $res = $this->with('store')->findWhere($map);
	}


	/**
	 * 查询店铺是不是默认店铺
	 * @param $data ['uid'=>1,'sid'=>1]
	 * @return mixed
	 */
	public function isDefault($data)
	{
		return $this->model->where($data)->first();
	}


	/**
	 *  获取店铺信息
	 * @param $userId
	 * @param $storeId
	 * @return mixed
	 */
	public function getStoreByUserIdStoreId($userId, $storeId)
	{
		$where = empty($storeId) ? ['uid' => $userId] : ['uid' => $userId, 'sid' => $storeId];
		return $this->with('store')->findWhere($where);
	}

	/**
	 * 获取用户常驻店铺
	 * @param $user_id
	 * @return mixed
	 */
	public function getUserPermanentStore($user_id)
	{
		return $this->model->where(['uid' => $user_id, 'is_default' => 1])->first();
	}

	/**
	 * 店铺是否是默认店铺
	 * @param $userId
	 * @param $storeId
	 * @return mixed
	 */
	public function isDefaultStore($userId, $storeId)
	{
		return $this->findByField(['uid' => $userId, 'sid' => $storeId])->first();
	}


	/**
	 * 获取店铺列表
	 * @param $userId
	 * @param $roleType
	 * @return mixed
	 */
	public function getStoresByUserIdRoleType($userId, $roleType)
	{
		return $this->with('store:id,name,logo')->findWhere(['uid' => $userId, 'rid' => $roleType]);
	}

	/**
	 * 获取店铺列表
	 * @param $userId
	 * @return mixed
	 */
	public function getStoresByUserId($userId)
	{
		return $this->model->select(['uid','sid'])->with(['store'=>function($v){
			$v->select(['id','name','logo'])->with('picture:id,image');
		}])->Where(['uid' => $userId])->distinct('sid')->get()->toArray();
	}

	public function getRoleListByStoreIdUserId($storeId,$userId){
		return $this->model->select(['rid'])->with('role:id,name')->Where(['uid' => $userId,'sid'=>$storeId])->distinct('uid')->get()->toArray();
	}
	/**
	 * 获取用户店铺角色
	 * @param $userId
	 * @param null $storeId
	 * @param null $roleType
	 * @return mixed
	 */
	public function getRolesInfoByType($userId, $storeId = null, $roleType = null)
	{
		if (!empty($storeId) && !empty($roleType)) {
			$where = ['uid' => $userId, 'sid' => $storeId, 'rid' => $roleType];
		} else if (!empty($storeId)) {
			$where = ['uid' => $userId, 'sid' => $storeId];
		} else if (!empty($roleType)) {
			$where = ['uid' => $userId, 'rid' => $roleType];
		} else {
			$where = ['uid' => $userId];
		}
		return $this->with('store')->findWhere($where);
	}

	/**
	 * 店铺添加理发师
	 * @param $userId
	 * $* @param $storeId
	 * @param $isDefault
	 * @return mixed
	 */
	public function addBarber($userId, $storeId, $isDefault)
	{
		return $this->create(['sid' => $storeId, 'uid' => $userId, 'is_work' => 1, 'is_default' => $isDefault, 'rid' => config('constant.role.barber')]);
	}


	/**
	 * 根据角色获取店铺的员工列表
	 * @param $role
	 * @param $storeId
	 * @param null $selfId
	 * @param bool $flag
	 * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model[]|mixed[]
	 */
	public function getUserInfoByRoleAndStoreId($role, $storeId, $selfId=null, $flag = true)
	{
		$where = empty($role) ?  ['sid' => $storeId] : ['rid' => $role, 'sid' => $storeId];
		return  $this->model->with(['user'=>function($v){
			$v->select(['id','nick','portrait'])->with('picture:id,image');
		}])->where($where)->when($flag, function ($v) use ($selfId) {
			$v->where('uid', '<>', $selfId);
		})->groupBy('uid')->orderBy('uid', 'desc')->get();
	}

	/**
	 * 新增更新角色设置
	 * @param $userId
	 * @param $storeId
	 * @param $role
	 * @return array
	 */
	public function setRole($userId, $storeId, $role)
	{
		$current = $this->findWhere(['uid' => $userId, 'sid' => $storeId], ['uid', 'sid', 'rid', 'is_default', 'is_work'])->toArray();
		$res = true;
		if (!empty($current)) {
			$isDefault = $current[0]['is_default'];
			$isWork = $current[0]['is_work'];
			$current = array_column($current, null, 'rid');
			// 正向比对
			foreach ($role as $v) {
				// 存在于两者共存
				if (isset($current[$v])) {
					$list['existed'][] = $current[$v];
				} else {
					$res = $this->create([
						'uid'        => $userId,
						'sid'        => $storeId,
						'rid'        => $v,
						'is_work'    => $isWork,
						'is_default' => $isDefault
					]);
				}
			}
			foreach ($current as $k) {
				in_array($k['rid'], $role) ? $delList['existed'][] = $k : $res = $this->deleteWhere($k);
			}
		}
		return $res;
	}

	/**
	 * 删除角色设置
	 * @param $userId
	 * @param $storeId
	 * @return int
	 */
	public function delRole($userId, $storeId)
	{
		$info = $this->model->where(['uid' => $userId, 'sid' => $storeId])->first();
		$this->deleteWhere(['uid' => $userId, 'sid' => $storeId]);
		return $this->create(['uid' => $userId, 'sid' => $storeId, 'rid' => 0, 'is_default' => $info->is_default, 'is_work' => $info->is_work, 'created_at' => time()]);
	}

	/**
	 * 去获取用户的角色列表
	 * @param $userId
	 * @param $storeId
	 * @return mixed
	 */
	public function getRoleList($userId, $storeId)
	{
		return $this->findWhere(['uid' => $userId, 'sid' => $storeId])->pluck('rid')->toArray();
	}

	/**
	 * 获取入职天数
	 * @param $user_id
	 * @param $store_id
	 * @return mixed
	 */
	public function getWorkDays($user_id, $store_id)
	{
		return $this
			->model
			->selectRaw('DATEDIFF(now(),created_at) + 1 as days')
			->where('uid', $user_id)
			->where('sid', $store_id)
			->first();

	}

	/**
	 * 同级别理发师
	 */
	public function getSameLevel($user_id, $store_id)
	{
		$user_id_array = $this->model->select([
			'uid'
		])->where('sid', $store_id)
			->where('rid', 2)
			->where('uid', '<>', $user_id)
			->get();

		$user_id_array = empty($user_id_array) ? [] : array_column($user_id_array->toArray(), 'uid');
		return empty($user_id_array) ? [] : $user_id_array;
	}


	/**
	 *  获取店铺的所有员工ID
	 * @param $storeId
	 * @return mixed
	 */
	public function getUserListByStoreId($storeId)
	{
		return $this->model
			->select('uid')
			->with([
				'user' => function ($v) {
					$v->select(['id', 'nick', 'portrait'])->with('picture:id,image');
				}
			])
			->where('sid', '=', $storeId)
			->distinct('uid')
			->get()
			->toArray();
	}

	public function getBaseWage($user_id, $store_id)
	{
		return $this->model
			->where('uid', $user_id)
			->where('rid', 2)
			->where('sid', $store_id)
			->first()
			->salary;
	}

	/**
	 * 删除理发师
	 * @param $store_id
	 * @param $user_id
	 * @return int
	 */
	public function delBarber($store_id, $user_id)
	{

		return $this->deleteWhere(['uid' => $user_id, 'sid' => $store_id]);
	}

	/**
	 * 设置员工基本工资
	 * @param $storeId
	 * @param $userId
	 * @param $salary
	 * @return mixed
	 */
	public function setBaseSalary($storeId, $userId, $salary)
	{
		return $this->model->where(['sid' => $storeId, 'uid' => $userId])->update(['salary' => $salary]);
	}

	/**
	 * 查询员工的基本工资
	 * @param $storeId
	 * @param $userId
	 * @param $role
	 * @return mixed
	 */
	public function getBaseSalary($storeId, $userId, $role)
	{
		return $this->model->where(['sid' => $storeId, 'uid' => $userId, 'rid' => $role])->value('salary');
	}

	/**
	 * 计算员工的每日的基本工资
	 * @param $storeId
	 * @param $userId
	 * @param $role
	 * @param $date
	 * @return float|int
	 */
	public function getUserDailySalary($storeId, $userId, $role, $date)
	{
		$baseSalary = $this->model->where(['sid' => $storeId, 'uid' => $userId, 'rid' => $role])->first();

		$isWorked = (new ScheduleRepository())->isWorked($storeId, $userId, $date);

		$days = date('t', $date);

		$hasBaseSalary = isset($baseSalary) ?
			($baseSalary->is_default == 1 ? (isset($isWorked) ? ($isWorked->status ? true : false) : true) : (isset($isWorked) ? ($isWorked->status ? true : false) : false))
			: false;
		return $hasBaseSalary ? round((floatval($baseSalary->salary) / floatval($days)), 2) : 0;
	}


	/**
	 * 判断用户是否是店铺的店长
	 * @param $storeId
	 * @param $userId
	 * @return bool
	 * @throws NotFoundException
	 */
	public function isStoreBoss($storeId,$userId){
		$boss = $this->model->where(['sid'=>$storeId,'uid'=>$userId,'rid'=>config('constant.role.manager')])->first();
		if(empty($boss)){
			throw  new NotFoundException(['msg'=>'对不起，您不是这家店铺的店长，没有操作权限！']);
		}
		return true;
	}


	public function getSoreEmployeeBaseSalary($store_id){
	  return $this->model->where('sid','=',$store_id)->distinct('uid')->sum('salary');
    }
}
